using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

using Storyteller.Framework.Math;

namespace Storyteller.Framework.Graphics
{
	public struct CharacterData
	{
		public short Width, Height;
		public short OffsetX, OffsetY;
		public short AdvanceX, AdvanceY;
		public TextureRegion TextureRegion;
	}
	
	public class Font
	{
		public int Height { get; protected set; }
		public Texture Texture { get; protected set; }
		
		public CharacterData this[short i]
		{
			get
			{
				if(characters.ContainsKey(i))
					return characters[i];
				else
					return characters[(short)' '];
			}
		}

		public Font(string filePath, Texture texture, TextureDictionary textureDictionary)
		{
			XDocument xmlDocument = XDocument.Load(filePath);
			
			Height = int.Parse((from f in xmlDocument.Descendants("height") select f).First().Value);
			Texture = texture;

			var nodes = xmlDocument.Descendants("character");
			foreach(var node in nodes)
			{
			    string id = node.Element("id").Value;
				short character = short.Parse(node.Element("id").Value);
				
			    CharacterData data = new CharacterData();
				data.OffsetX = short.Parse(node.Element("offsetX").Value);
				data.OffsetY = short.Parse(node.Element("offsetY").Value);
				data.AdvanceX = short.Parse(node.Element("advanceX").Value);
				data.AdvanceY = short.Parse(node.Element("advanceY").Value);
				data.Width = short.Parse(node.Element("width").Value);
				data.Height = short.Parse(node.Element("height").Value);
			    if(data.Width != 0 && data.Height != 0)
			        data.TextureRegion = textureDictionary.GetRegion(id + ".png");
				
			    characters[character] = data;
			}
		}
		
		public Vector2 MeasureString(string s)
		{
			float width = 0;
			
			foreach(var c in s)
			{
				width += this[(short)c].Width;
			}
			
			return new Vector2(width, Height);
		}
		
		Dictionary<short, CharacterData> characters = new Dictionary<short, CharacterData>();
	}
}
